<template>
  <div>
    <Modal v-model="roleModalVisible">
      <template #header>
        <div>
          <span style="font-size: 16px;font-weight: bold">添加角色</span>
        </div>
      </template>
      <div style="padding: 8px 16px">
        <Form :model="roleInfoForm">
          <FormItem label="角色名称">
            <Input v-model="roleInfoForm.roleName"></Input>
          </FormItem>
          <FormItem label="角色描述">
            <Input v-model="roleInfoForm.description" type="textarea"></Input>
          </FormItem>
          <FormItem label="权限">
            <Tree
                ref="routeTree"
                :data="routeData"
                show-checkbox
                expand-node
            ></Tree>
          </FormItem>
        </Form>
      </div>
      <template #footer>
        <Button type="default" @click="roleModalVisible=false">取消</Button>
        <Button type="primary" @click="addrole">确定</Button>
      </template>
    </Modal>
  </div>

</template>
<script setup>
import {useRoleStore} from "@/module-base/stores/roleStore.js";
import {addRole as addRoleApi, addPermissionToRole} from "@/module-base/api/sysManage.js";
import {storeToRefs} from "pinia";
import {ref} from "vue";

const {roleModalVisible, roleInfoForm, routeData} = storeToRefs(useRoleStore())
const routeTree = ref(null)

const emit = defineEmits(['addRoleComplete'])

async function addrole() {
  try {
    const treeData = routeTree.value.getCheckedNodes()
    const treeDataIds = treeData.map(treeItem => treeItem.id)
    console.log(treeDataIds)
    debugger
    // 维护角色信息
    const rs = await addRoleApi(roleInfoForm.value)
    // 维护角色权限
    const rolePermissionRs = await addPermissionToRole({
      roleId: rs.data.id,
      permissionIds: treeDataIds
    })
    console.log(rolePermissionRs)
    if (rs.success) {
      // handleGetList()
      emit('addRoleComplete')
    }
  } catch (error) {
    console.log(error)
  }
}

/**
 * 路由树形组件*/
function getCheckedNodes(nodes) {
  console.log(routeTree.value.getCheckedNodes())
}

function getSelectedNodes(nodes) {
  console.log(nodes)
}
</script>
<style scoped>

</style>